/**
 * @author Alfort Robert - Köckinger Martin
 * This Class handles the encoding functionality
 * @version 2.1
 */

package at.fhj.itm;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

/** Call when QRCodeEncode calls calculation function
 * @params String
 * @params Integer
 * @params Bitmap
 * @see android.os.AsyncTask
 */
public class QREncoder extends AsyncTask<String, Integer, Bitmap> {

	private Bitmap bm; /** Creating a Bitmap for handling Code */

	/**
	 * Implements the handle code for encodeing Images.
	 * @params String input
	 * @return Bitmap
	 * @see http://code.google.com/apis/charttools/index.html
	 */
	public Bitmap getQRImage(final String input) {
		Log.i("Request", "Threading started");
		Log.i("Data:", "Recived input: " + input);

		URL aURL;
		try {
			/*
			 * defining encodeing URL (Google Charts API)
			 */
			aURL = new URL(
					"http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF-8&chl="
							+ URLEncoder.encode(input.toString(), "UTF-8"));
			/*
			 * Addresseintrag
			 * MECARD:N:Robert Alfort;TEL:+436641453065;URL:http://www.roteskreuz.at;EMAIL:robert.alfort@st.roteskreuz.at;ADR:8600 Bruck/Mur Lammingfeldsiedlung F3/4;NOTE:Memo;;
			 */
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			/*
			 * Write Data to Bitmap
			 */
			bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			// return bm;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bm;
	}

	/**
	 * Calculating data in Background
	 * Interface is accessable
	 * @params String... inputData
	 * @return Bitmap
	 */
	@Override
	protected Bitmap doInBackground(String... inputData) {
		String input = inputData[0];
		return this.getQRImage(input);
	}

	/**
	 * After Calculating Data
	 * Setting Image to ImageView
	 * @params Bitmap result
	 */
	@Override
	protected void onPostExecute(Bitmap result) {
		Log.i("BACKGROUND", "Data calculated.");
		QRCodeEncode.imgView.setImageBitmap(result); // Set Bitmap to imageview
	}

}
